클래스

✒️ 2025-05-19 10:24 내용 수정

Do it! 점프 투 파이썬(2017년 발행) 내용을 정리


객체를 표현하기 위한 설명 양식이자, 객체 지향 프로그램의 기본적인 사용자 정의 데이터형

class ClassName:
	pass

인스턴스(Instance)

>>> class Car:
...     pass
...

>>> a = Car()
>>> b = Car()

메서드(Method)

class ClassName:
	def fnName(args):
		# 수행할 내용
>>> class Car:
...     def testFn(self, first, second):
...         print(f"{first} and {second}")
...
>>> a = Car()
>>> a.testFn("apple", "banana")
apple and banana
>>> class Fruit:
...     def setdata(self, name, color):
...         self.name = name
...         self.color = color
...
>>> a = Fruit()
>>> a.setdata("apple", "red")
>>> a.name
'apple'
>>> a.color
'red'
# 클래스.py
class Fruit:
    def setdata(self, name, color):
        self.name = name
        self.color = color
    def printfruit(self):
        print(self.color, self.name)
    def fullname(self):
        return self.color + " " + self.name

a = Fruit()
a.setdata("apple", "red")
a.printfruit()
b = a.fullname()
print(b)

python_class 1.png


생성자

# 클래스.py
class Fruit:
	def __init__(self, name, color):
        self.name = name
        self.color = color
    def setdata(self, name, color):
        self.name = name
        self.color = color
    def printfruit(self):
        print(self.color, self.name)
    def fullname(self):
        return self.color + " " + self.name
a = Fruit("grape", "green")
a.printfruit()
print(a.fullname())

python_class 2.png

소멸자

class 클래스명:
	def __del__(self):
		# 수행할 내용

# 객체 소멸
del 클래스변수

클래스 변수

class Family:
    lastname = "kim"

a = Family()
b = Family()
print(a.lastname)
print(b.lastname)

Family.lastname = "park"
print(a.lastname)
print(b.lastname)

python_class 3.png